// detail.js
const EventEmitter = require('../../common/EventEmitter.js');
const requester = require('../../common/requester.js');
const config = require('../../common/config.js');
const util = require('../../common/util.js');
const fans = require('../../utils/fans.js');
const $$onLoad = require('../../appLoaded/onLoad');
const app = getApp();

Page({
    pageIndex: 1,
    data: {
        actions: ['addImage', 'goPicList'],
        commentContent: '',
        toView: '',
        hideViewMore: true,
        hasLoaded: false,
        inputStatus: false,
        isAudit: true,
        isAuthed: true,
        sendButtonEnable: false
    },

    onLoad: function (param) {
        $$onLoad()
            .then(() => {
                let isAudit = app.globalData.isAudit,
                    isAuthed = app.globalData.isAuthed;

                this.setData({
                    isAudit,
                    isAuthed,
                    id: param.id
                });

                if (isAuthed) {
                    this.init();
                }
            });
    },

    init: function () {
        this.getImgData();
        this.getCommentData();
        this.getRecommendResources(false);

        EventEmitter.addListener('backFormComment', () => {
            this.getCommentData();
        });
        this.setData({
            scrollTop: 'top',
            isAudit: app.globalData.isAudit
        })
    },
    // 单个图片点击
    imageTap: function (e) {
        let image = e.currentTarget.dataset.image;
        let curImageUrl = image.picUrl || image.smallPicUrl;
        let urls = [curImageUrl];
        wx.previewImage({
            current: curImageUrl,
            urls: urls
        });
    },

    /**
     * 进入评论列表页面。
     */
    goCommentDetail: function (e) {
        let id = e.currentTarget.id;
        let image = e.currentTarget.dataset.image;
        image && wx.navigateTo({
            url: '../comment/comment?id=' + id + "&resourceId=" + image.id
        });
    },
    //获取评论
    getCommentData: function () {
        let me = this;
        me.getCommentDataList();
    },
    getCommentDataList: function () {
        let me = this;
        let commentType = 2;
        requester.request({
            url: requester.service.commentList,
            data: {
                resourceId: me.data.id,
                commentType: commentType,
                pageIndex: 1,
                pageSize: 5
            }
        }).then(res => {
            if (res.data && ((res.code != 0) || (!res.data.length))) {
                me.setData({
                    hideViewMore: true
                });
                return;
            }
            let comments = res.data;
            me.setData({
                hideViewMore: comments && comments.length < 5,
                commentList: comments,
                commentCount: comments ? comments.length : 0
            });
        });
    },
    // 进入用户详情页面
    goUserDetail: function (e) {
        if(this.data.isAudit){
            return
        }
        let userId = e.currentTarget.dataset.userId;
        wx.redirectTo({
            url: `../thirdUser/thirdUser?userId=${userId}`
        });
    },

    //每次进入页面更新评论数和点赞数
    getImgData: function () {
        let id = this.data.id;
        requester.request({
            url: requester.service.resourceDetail,
            data: {
                resourceId: id,
            }
        }).then(res => {
            this.setData({
                image: res.data.userResource,
                showPicView: true,
                isFollowed: res.data.user.isFollowed,
                userId: res.data.userResource.userId
            });
            this.ensureLikeStatus();
        });
    },

    ensureLikeStatus: function () {
        let me = this,
            image = this.data.image;
        wx.getStorage({
            key: config.storage.keyImageLikeIdList,
            success: function (res) {
                let li = res.data || [];
                li.forEach(sId => {
                    if (image.id == sId) {
                        image.isFavor = true;
                        image.likeCount = Number(image.isFavor) + 1
                    }
                });
                me.setData({
                    image: image
                });
            }
        })
    },

    /**
     * 点赞
     */
    favorTap: function (e) {
        let me = this;
        let image = e.currentTarget.dataset.image;
        let like = image.isFavor;
        requester.request({
            url: !like ? requester.service.favorComment : requester.service.cancelImageLike,
            data: {
                resourceId: image.id,
                commentType: 1,
                content: ''
            }
        }).then(res => {
            let item = me.data.image;
            item.isFavor = !item.isFavor;
            item.likeCount = !like ? Number(item.likeCount) + 1 : Number(item.likeCount) - 1
            me.setData({
                image: item
            });

            if (res.code == 0) {
                let li = wx.getStorageSync(config.storage.keyImageLikeIdList) || [];
                if (!like) {
                    li.push(image.id);
                } else {
                    li.forEach((sId, index) => {
                        if (sId == image.id) {
                            li.splice(index, 1);
                        }
                    });
                }
                wx.setStorageSync(config.storage.keyImageLikeIdList, li)
            } else if (res.code == 2006) {
                let li = wx.getStorageSync(config.storage.keyImageLikeIdList) || [];
                li.push(image.id);
                wx.setStorageSync(config.storage.keyImageLikeIdList, li)
            }
        });
    },

    onShareAppMessage: function (res) {
        return {
            title: '图说馆，送你一张美图',
            path: '/pages/pictureDetail/pictureDetail?id=' + this.data.id,
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }
    },

    addImage: function (e) {
        wx.chooseImage({
            count: 1,
            success: (res) => {
                let tempFilePath = res.tempFilePaths[0];
                wx.navigateTo({
                    url: `../send/send?url=${tempFilePath}&from=main`
                });
            }
        });
    },

    gotoProfilePage: function (e) {
        wx.switchTab({
            url: '../me/me'
        });
    },

    imgLoaded: function () {
        setTimeout(() => {
            this.setData({
                hasLoaded: true
            })
        }, 240)
    },

    onPullDownRefresh: function () {
        this.setData({
            isRefreshing: true
        });
    },
    onPullDownStop: function () {
        wx.stopPullDownRefresh();
        this.setData({
            isRefreshing: false
        });
    },

    loadMore: function (e) {
        this.getRecommendResources(true);
    },
    /**
     * 获取数据。
     * @param isLoadMore boolean 是否是加载更多。
     */
    getRecommendResources: function (isLoadMore) {
        let me = this;

        if (isLoadMore) {
            this.pageIndex++;
        } else {
            this.pageIndex = 1;
        }

        this.getResourceList()
            .then(resourceLi => {
                    util.addModeToList(resourceLi);
                    if (isLoadMore) {
                        let tmpLi = me.data.recommendList || [];
                        resourceLi = tmpLi.concat(resourceLi)
                    }
                    me.setData({
                        recommendList: resourceLi
                    }, () => {
                        this.onPullDownStop();
                    })
                }
            );
    },

    /**
     * 获取资源列表
     */
    getResourceList: function () {
        let pageIndex = this.pageIndex;
        return requester.request({
            url: requester.service.resourceList,
            data: {
                pageIndex: pageIndex
            }
        }).then(res => {
            return res.data.groupList;
        });
    },
    //详情页查看更多图片，在当前页面上刷新
    cellTap: function (e) {
        var curImage = e.currentTarget.dataset.image;
        this.setData({
            recommendList: [],
            hasLoaded: false,
            showPicView: false
        });
        this.data.id = curImage.id;
        this.init()
    },

    follow: function () {
        let id = this.data.userId;
        let me = this;
        fans.follow(id)
            .then((res) => {
                if (res) {
                    wx.showToast({
                        title: '关注成功'
                    });
                    me.setData({
                        isFollowed: 1
                    })
                }
            })
    },
    unfollow: function () {
        let id = this.data.userId;
        let me = this;
        fans.unfollow(id)
            .then((res) => {
                if (res) {
                    wx.showToast({
                        title: '已取消关注'
                    });
                    me.setData({
                        isFollowed: 0
                    })
                }
            })
    }
});